package ua.amsoft.brelok.widget;

import ua.amsoft.brelok.manager.WidgetUpdateManager;
import ua.amsoft.brelok.service.UpdateService;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

/**
 * @author Tair Mustafaiev
 */
public class UpdateStopReceiver extends BroadcastReceiver {
    
    public static final String STOP_RECEIVER_ACTION = "UpdateStopReceiverAction";
    
    private static final String TAG = UpdateStopReceiver.class.getName();
    
    @Override
    public void onReceive(final Context context, final Intent intent) {
        Log.i(UpdateStopReceiver.TAG, "UpdateStopReceiver received intent and started execution");
        final Intent updateServiceIntent = new Intent(context, UpdateService.class);
        final AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        final PendingIntent pendingIntentToCancel = PendingIntent.getService(context, 0,
                updateServiceIntent, 0);
        // Last update for widget should be in the end of the working day
        updateWidget(context);
        alarm.cancel(pendingIntentToCancel);
        Log.i(UpdateStopReceiver.TAG, "UpdateService was cancelled for few hours");
        Log.i(UpdateStopReceiver.TAG, "UpdateStopReceiver finished execution");
    }
    
    /**
     * Updates widget
     * 
     * @param context - {@link Context}
     */
    private void updateWidget(final Context context) {
        final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
        final ComponentName widget = new ComponentName(context, BrelokWidgetProvider.class);
        final int[] appWidgetIds = appWidgetManager.getAppWidgetIds(widget);
        for (final int appWidgetId : appWidgetIds) {
            WidgetUpdateManager.updateAppWidget(context, appWidgetManager, appWidgetId);
        }
    }
    
}
